package com.stylefeng.guns.rest.modular.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.stylefeng.guns.biz.acct.LoginBizImpl;
import com.stylefeng.guns.biz.acct.WebUserOptBizImpl;
import com.stylefeng.guns.common.bo.AuthUserBo;
import com.stylefeng.guns.common.dto.acct.*;
import com.stylefeng.guns.common.dto.common.ResultData;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.persistence.model.Webuser;
import com.stylefeng.guns.common.service.redis.RedisClient;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.support.RestConstant;
import com.stylefeng.guns.modular.system.service.IWebuserService;
import com.stylefeng.guns.modular.system.service.IAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;


/**
 * @author carloszhang
 * <p>
 * 操作不需要登录的情况
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/api/person")
@Api(value = "非登录鉴权相关接口", produces = "application/json")
@Slf4j
public class UserNoAuthController extends BaseController {

    @Autowired
    private LoginBizImpl loginBizImpl;


    @Autowired
    private WebUserOptBizImpl webUserOptBizImpl;


    @Autowired
    private IAreaService iAreaService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private IWebuserService webUserService;

    private Boolean kaptchaOpen = true;




    @PostMapping(value = "/login/req")
    @ApiOperation(value = "登录")
    public ResultData<LoginResp> logIn(@Valid @RequestBody LoginReq req, HttpServletResponse response) {
        Webuser webuser = loginBizImpl.validateLoginUser(req.getMobileNo(), req.getCipher());//校验支付密码
        AuthUserBo authUserBo = loginBizImpl.LoginCacheUser(webuser);//增加缓存
        LoginResp resp = new LoginResp();
        {
            resp.setUserId(webuser.getId());
            resp.setOptResult(Boolean.TRUE);
            resp.setAccessToken(authUserBo.getAuthKey());

            resp.setCity(webuser.getCity());
            resp.setProvince(webuser.getProvince());
            try {
                resp.setProvinceDesc(webuser.getProvince() != null ?
                        iAreaService.selectNameByCacheCode(webuser.getProvince().toString())
                        : StringUtils.EMPTY);
                resp.setCityDesc(webuser.getCity() != null ?
                        iAreaService.selectNameByCacheCode(webuser.getCity().toString())
                        : StringUtils.EMPTY);
            } catch (Exception e) {
                resp.setProvinceDesc(StringUtils.EMPTY);
                resp.setCityDesc(StringUtils.EMPTY);
            }
        }

        {
            response.setHeader(RestConstant.ACCESS_TOKEN, authUserBo.getAuthKey());
            response.setHeader(RestConstant.ACCESS_HEADERS, RestConstant.ACCESS_TOKEN);

        }
        return ResultData.createResult(resp);//返回登录成功
    }

    @GetMapping(value = "/logout/req")
    @ApiOperation(value = "退出登录")
    public ResultData<LoginResp> logOut(HttpServletRequest request) {

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = (String) headerNames.nextElement();
            log.info("头信息header:{},value:{}", name, request.getHeader(name));
        }

        String token = request.getHeader(RestConstant.AUTH_USER_CACHE_KEY);//如不存在则不做删除处理
        if (StringUtils.isNotBlank(token)) {
            loginBizImpl.delCacheUser(token);
        }
        LoginResp resp = new LoginResp();
        resp.setOptResult(Boolean.TRUE);
        return ResultData.createResult(resp);//返回登录成功
    }


    @GetMapping(value = "/forget/cipher/req/tmp")
    @ApiOperation(value = "测试")
    public ResultData<ForgetCipherResp> forgetCipherTmp() {
        return ResultData.createResult(new ForgetCipherResp());
    }

    @PostMapping(value = "/avatar")
    @ApiOperation(value = "设置头像信息")
    public ResultData<AvatarResp> uploadAvatarInfo(@Valid @RequestBody AvatarReq req) {
        if (StringUtils.isBlank(req.getAvatarBase64())) {
            throw new GunsException(BizExceptionEnum.PARAM_ERROR);
        }
        AvatarResp result = webUserOptBizImpl.uploadAvatarInfo(req);
        return ResultData.createResult(result);
    }


    @PostMapping("/now")
    @ApiOperation(value = "查询服务器当前时间", notes = "返回服务器当前时间戳")
    public ResultData<Long> getNow() {
        return ResultData.createResult((new Date()).getTime());
    }

    @Autowired
    Producer producer;

    private static final int width = 105;
    private static final int height = 35;
    private static final int lineWidth = 2;//干扰线的长度=1.414*lineWidth
    private static final int count = 200;

    /**
     * 生成验证码
     */
    @RequestMapping("/kaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) {
        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // response.setContentType("image/png");

        // 在内存中创建图象
        final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        final Graphics2D graphics = (Graphics2D) image.getGraphics();

        // 设定背景颜色
        graphics.setColor(Color.WHITE); // ---1
        graphics.fillRect(0, 0, width, height);
        // 设定边框颜色
//		graphics.setColor(getRandColor(100, 200)); // ---2
        graphics.drawRect(0, 0, width - 1, height - 1);

        final Random random = new Random();
        // 随机产生干扰线，使图象中的认证码不易被其它程序探测到
        for (int i = 0; i < count; i++) {
            graphics.setColor(getRandColor(150, 200)); // ---3
            final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
            final int y = random.nextInt(height - lineWidth - 1) + 1;
            final int xl = random.nextInt(lineWidth);
            final int yl = random.nextInt(lineWidth);
            graphics.drawLine(x, y, x + xl, y + yl);
        }

        // 取随机产生的认证码(4位数字)
        final String resultCode = producer.createText();
        log.info(resultCode);
        for (int i = 0; i < resultCode.length(); i++) {
            // 设置字体颜色
            graphics.setColor(Color.BLACK);
            // 设置字体样式
            graphics.setFont(new Font("Arial", Font.BOLD, 24));
            // 设置字符，字符间距，上边距
            graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
        }
        // 将认证码存入SESSION
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, resultCode);
        // 图象生效
        graphics.dispose();
        // 输出图象到页面
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成验证码Redis存储
     */
    @RequestMapping("/kaptcharedis")
    public void getKaptchaRedis(HttpServletRequest request, HttpServletResponse response) {
        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // response.setContentType("image/png");

        // 在内存中创建图象
        final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        final Graphics2D graphics = (Graphics2D) image.getGraphics();

        // 设定背景颜色
        graphics.setColor(Color.WHITE); // ---1
        graphics.fillRect(0, 0, width, height);
        // 设定边框颜色
//		graphics.setColor(getRandColor(100, 200)); // ---2
        graphics.drawRect(0, 0, width - 1, height - 1);

        final Random random = new Random();
        // 随机产生干扰线，使图象中的认证码不易被其它程序探测到
        for (int i = 0; i < count; i++) {
            graphics.setColor(getRandColor(150, 200)); // ---3
            final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
            final int y = random.nextInt(height - lineWidth - 1) + 1;
            final int xl = random.nextInt(lineWidth);
            final int yl = random.nextInt(lineWidth);
            graphics.drawLine(x, y, x + xl, y + yl);
        }

        // 取随机产生的认证码(4位数字)
        final String resultCode = producer.createText();
        log.info(resultCode);
        for (int i = 0; i < resultCode.length(); i++) {
            // 设置字体颜色
            graphics.setColor(Color.BLACK);
            // 设置字体样式
            graphics.setFont(new Font("Arial", Font.BOLD, 24));
            // 设置字符，字符间距，上边距
            graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
        }
        // equid=2131231&rank=1321
        String param = request.getQueryString();
        String[] temp = param.split("&");
        String equid = temp[0].split("=")[1];
        redisClient.set(equid,resultCode);
        // 图象生效
        graphics.dispose();
        // 输出图象到页面
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Color getRandColor(int fc, int bc) { // 取得给定范围随机颜色
        final Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        final int r = fc + random.nextInt(bc - fc);
        final int g = fc + random.nextInt(bc - fc);
        final int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
}